// pages/index/index.js 
import { comm } from "../../utils/httpRequest";
import { util } from "../../utils/util.js";
const app = getApp();
let poster;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    StatusBar: app.globalData.StatusBar,
    Width: app.globalData.Width,
    Right: app.globalData.Right,
    Height: app.globalData.Height,
    loginStatus:false,
    authenticationSwitch:0,
    showShareBtn:false,
    textareaValue:false,
    t_num:0, 
    detail:{
      card_diy_bg:'1',
      cardbackground:'1'
    },
    share:'',
    modelshow: false,
    cardName:"",
    cardId:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options && options.sourceUrl){
      this.setData({
        sourceUrl:options.sourceUrl
      })
    }
    if(options && options.share){
      this.setData({
        share:options.share
      })
      this.isShare()
    } 
    if(options && options.card_id){
      this.setData({card_id:options.card_id})
    } 
    if(options && options.scene){
      this.setData({card_id:options.scene.split('-')[0],scene:options.scene})
    }
  },
  onShow() {
    var select_card_info = wx.getStorageSync('select_card_info')
    if(select_card_info){ 
          this.setData({
            cardId:select_card_info.card_id,
            cardName : select_card_info.name+'-'+select_card_info.position
          })
   }
    this.getDetail();
    this.getCollect();
    this.getAuthentication_switch ()   
  },
  getAuthentication_switch(){
    var that = this;  
    comm.cjRequest({url: "/wxapi/getConfigSwitch", data:{}})
      .then((res) => {  
        if(res.data.code == 1){
          that.setData({
            config: res.data.data
          })
        } 
    })
  },
  goViewCardUser(){ 
    wx.navigateTo({
      url: '/pages/viewCardUser/index?card_id='+this.data.detail.id+'&user_id='+this.data.detail.user_id,
    })
  },
  goAddcard(){
    var userInfo = wx.getStorageSync('userInfo');
    if(!userInfo){
      comm.goLoginPage()
      return false;
    }
    wx.navigateTo({
      url: '/pages/addCard/index',
    })
  },
  isCopyWechat() {  
    var that = this;  
    //因为返回的是promise对象，所以通过.then来获取resolve出来的请求成功的返回数据 
    comm.cjRequest({url : "/wxapi/isCopyWechat",data:{card_id : that.data.card_id}})
      .then((res) => { 
        console.log(res);
    })
  },
  isShare() {  
    var that = this;  
    //因为返回的是promise对象，所以通过.then来获取resolve出来的请求成功的返回数据 
    comm.cjRequest({url : "/wxapi/isShare",data:{card_id : that.data.card_id},})
      .then((res) => { 
        console.log(res);
    })
  },
  isClickEmail() {  
    var that = this;  
    //因为返回的是promise对象，所以通过.then来获取resolve出来的请求成功的返回数据 
    comm.cjRequest({url : "/wxapi/isClickEmail",data:{card_id : that.data.card_id},})
      .then((res) => { 
        console.log(res);
    })
  },
 
  getCollect() {  
    var that = this; 
    var userInfo = wx.getStorageSync('userInfo'); 
    //因为返回的是promise对象，所以通过.then来获取resolve出来的请求成功的返回数据
    var data = {
      url : "/wxapi/getCollect",
      data:{
        card_id : that.data.card_id
      } 
    }
 
    if(userInfo && userInfo.id){
      data.data.user_id = userInfo.id;
      data.token = true; 
    }
    
    comm.cjRequest(data)
      .then((res) => {
         that.setData({
          collect:res.data.data
         }) 
    })
  },
  getImpression() {  
    var that = this; 
    var userInfo = wx.getStorageSync('userInfo');  
    var data = {
      url : "/wxapi/getImpression",
      data:{ 
        card_id : that.data.card_id,
        card_user_id : that.data.detail.user_id
      }
    } 
    if(userInfo){
      data.data.user_id = userInfo.id
    }
    comm.cjRequest(data)
      .then((res) => {
         that.setData({
          impression:res.data.data
         }) 
    })
  },
  clickImpression(e) {  
    var that = this; 
    var userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      comm.goLoginPage()
      return false;
    }
    var index = e.currentTarget.dataset.index;
    var data = {
      url:"/wxapi/clickImpression",
      data:{
        impression_id:e.currentTarget.dataset.id,
        card_id:that.data.card_id , 
        user_id : userInfo.id
      },
      token : true
    }  
    comm.cjRequest(data)
      .then((res) => {
        if(res.data.code == 0){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
          return false;
        } 
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
        var impression = that.data.impression;  
        if(impression[index].check != 1){
          impression[index].check = 1
          impression[index].clickTotal = impression[index].clickTotal+1
        }else {
          impression[index].check = 0
          impression[index].clickTotal = impression[index].clickTotal-1
        }
        that.setData({
          impression:impression, 
        })
        console.log(res);
    })
  },
  clickCollect() {  
    var that = this; 
    var userInfo = wx.getStorageSync('userInfo');
    if(!userInfo || !userInfo.id){
      comm.goLoginPage()
      return false;
    }
    //因为返回的是promise对象，所以通过.then来获取resolve出来的请求成功的返回数据
    var data = {
      card_id:that.data.card_id ,
      user_id:userInfo.id ,
    };  
    var url = "/wxapi/clickCollect";
    
    comm.cjRequest({url: url, data:data,token:true})
      .then((res) => {
        if(res.data.code == 0){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
          return false;
        } 
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
        var collect = that.data.collect; 
        if(collect.collectStatus){
          collect.collectStatus = false;
          collect.collectTotal = Number(collect.collectTotal) - 1
        }else{
          collect.collectStatus = true;
          collect.collectTotal = Number(collect.collectTotal) + 1
        }
        that.setData({
          collect:collect,

        })
        console.log(res);
    })
  },
  handleLongPress: function() {
    var that = this;  
    //因为返回的是promise对象，所以通过.then来获取resolve出来的请求成功的返回数据 
    comm.cjRequest({url : "/wxapi/isLongPressWechatCode",data:{card_id : that.data.card_id},})
      .then((res) => { 
        console.log(res);
    })
  },
    // 拨打电话
    phone(){
      if(!this.data.phone){
        wx.showToast({
          title: '抱歉，此名片没有添加电话号码',
          icon:'none'
        })
        return false
      }
      var that = this;
      var phone = that.data.detail.phone+' '
      console.log(that.data.phone)
      wx.makePhoneCall({
        phoneNumber:phone,
        success(){
          comm.cjRequest({url : "/wxapi/isCallMe",data:{card_id : that.data.card_id},})
            .then((res) => { 
              console.log(res);
          })
        },
        fail(){}
      })
    },
    copyText(e){
      var type = e.currentTarget.dataset.type
      if(type == 'wechat_num'){
        var text = this.data.detail.wechat_num
        var tips = '微信号已复制成功，去微信搜索添加好友吧'
        if(!this.data.detail.wechat_num){
          wx.showToast({
            title: '抱歉，此名片没有添加微信号',
            icon:'none'
          })
          return false
        }
        this.isCopyWechat()
      }else if(type == 'email'){
        if(!this.data.detail.email){
          wx.showToast({
            title: '抱歉，此名片没有添加邮箱',
            icon:'none'
          })
          return false
        }
        var text = this.data.detail.email
        var tips = '邮箱账号已经复制成功，去发送邮件吧'
        this.isClickEmail()
      }
      wx.setClipboardData({
        data: text,
        success: function(res) {
          wx.getClipboardData({
            success: function(res) {
              wx.hideToast()
              wx.showModal({
                title: '提示',
                content: tips,
                showCancel:false, 
                confirmText:'知道了'
              })
            }
          })
        }
      })
    },
  becomeDealer(){
  //成为经销商
  this.setData({modelshow:true})

  },
  goCardHolder(){
    wx.navigateTo({
      url: '/pages/cardholder/index?sourceType=select&sourceUrl=my'
    })
  },
  onDialogColose(){
    this.setData({
      modelshow:false,
    })
  },
  onDialogConfirm(){
    comm.cjRequest({url: "/wxapi/supplier_request", data:{
      supplier_id: this.data.card_id,
      my_card_id: this.data.cardId
    }})
    .then((res) => {
      if(res.data.code == 0){
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
        return false;
      }
      wx.showToast({
        title: res.data.msg,
        icon:'none'
      }) 
    })
  },
  savePhone(e){
    wx.addPhoneContact({ 
      firstName:this.data.detail.name , 
      mobilePhoneNumber: this.data.phone+' ', //手机号 
      success: function () { 
        wx.showToast({
          title: '保存成功',
          icon:'none'
        })
      },
      fail: function () {
          wx.showToast({
            title: '保存失败',
            icon:'none'
          })
      }
    })
  },
  getDetail() {  
    wx.showLoading({
      title: '加载中',
    })
    var that = this;  
    var data = {
      card_id:that.data.card_id,  
      share:that.data.share
    };  

    if(wx.getStorageSync('userInfo')){
      data.user_id = wx.getStorageSync('userInfo').id
    } 
    var url = "/wxapi/getMyCardDetail"; 
    comm.cjRequest({url: url, data:data})
      .then((res) => {
        wx.hideLoading()
        if(res.data.code == 0){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
          setTimeout(function(){wx.navigateBack()},1200)
          return false;
        } 
        if(res.data.data.auditing_status != 1){
          var tip = res.data.data.auditing_status == 0 ? '名片正在审核中，请耐心等待' : '抱歉，此名片未通过平台审核';
          wx.showToast({
            title: tip,
            icon:'none'
          })
         setTimeout(function(){
          wx.switchTab({
            url: '/pages/connections/index',
          })
         },1200)
         return false
        }
        res.data.data.description = comm.formatRichText(res.data.data.description)
        that.setData({
          detail:res.data.data,
          phone:res.data.data.phone, 
        }) 
        
        console.log(res.data.data)
        that.getImpression();
    })
  },

  sendMsg(){
    var that = this;
    var userInfo = wx.getStorageSync('userInfo');
    if(!userInfo){
      comm.goLoginPage()
      return false;
    }
    if(!that.data.msg){
      wx.showToast({
        title: '请输入一些文字吧',
        icon:'none'
      })
      return false;
    }
    var data = {
      form_user_id:userInfo.id,
      to_user_id:that.data.detail.user_id,
      card_id : that.data.card_id,
      msg : that.data.msg
    }
    comm.cjRequest({url: '/wxapi/sendMsg', data:data,token:true})
      .then((res) => {
        if(res.data.code == 0){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
          return false;
        }
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        }) 
        that.setData({
          msg:'', 
          textareaValue:false
        })
        console.log(res);
    })
  },
  goBack(){
    wx.navigateBack()
  },
  textareaAInput(e){
    console.log(e.detail.value.length) 
    this.setData({t_num:e.detail.value.length})
    if(e.detail.value.length>0){
      this.setData({textareaValue:true,msg:e.detail.value,t_num:e.detail.value.length})
    }else{
      this.setData({textareaValue:false,msg:''})
    }
  },
  onScroll: function(e) { 
    this.setData({scrollTop:e.detail.scrollTop})
  },
  getWXcode() {
     wx.navigateTo({
       url: '../weixinCode/index',
     })
  },
  goProductList(){
    wx.navigateTo({
      url: '/pages/productList/index?sourceUrl=card'+'&user_id='+this.data.detail.user_id,
    })
  },
  goCaseList() {
    wx.navigateTo({
      url: '/pages/caseList/index?sourceUrl=card'+'&user_id='+this.data.detail.user_id,
    })
  },
 
  goDetail(e) {  
    wx.navigateTo({
      url: '/pages/detail/index?id='+e.currentTarget.dataset.id+'&sourceUrl='+e.currentTarget.dataset.sourceurl+'&phone='+this.data.detail.phone+'&wechat_num='+this.data.detail.wechat_num
    })
  },
  goImages() { 
    wx.navigateTo({
      url: '/pages/imagesDetail/index?id='+this.data.detail.images_id,
    })
  }, 
  goWebsite() { 
    wx.navigateTo({
      url: '/pages/website/index?s=card&user_id='+this.data.detail.user_id+'&website_id='+this.data.detail.website.id,
    })
  },
  
  goIndex(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  showModal(e) {
    console.log(this.data.detail.wechat_code_image)
    if(!this.data.detail.wechat_code_image){
      wx.showToast({
        title: '抱歉，此名片没有上传微信二维码',
        icon:'none'
      })
      return false;
    }
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.detail.images,
      current: e.currentTarget.dataset.url
    });
  }, 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    poster = this.selectComponent('#card_2')
  },
  ready() {
    this.setData({
      init: true
    })
  },
  getCardCode() { 
    if(this.data.detail.hideinfo_status == 1 && this.data.sharetype != 'admin'){
      this.showTips();
      return false;
    }
    var that = this;
     
    if (!that.data.init || !poster) return;
    wx.showLoading({
      title: '生成中...'
    })
    var data = {
      card_id:that.data.detail.id
    }
    var userInfo = wx.getStorageSync('userInfo'); 
    if(userInfo && that.data.detail.user_id == userInfo.id){
      data.sharetype = 'admin';
    }
    comm.cjRequest({
      url: '/wxapi/getCardCode',
      data: data,
      token: true
    }).then((res) => { 
      if (res.data.code == 0) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
        return false;
      }
      
      var imgsUrl ={
        avatar:that.data.detail.avatar, 
        minicode_image:res.data.data.minicode_image, 
      };
      if(that.data.detail.cardbackground){
        imgsUrl.cardbackground = that.data.detail.cardbackground;
      }
      if(that.data.detail.card_diy_bg){
        imgsUrl.cardbackground = that.data.detail.card_diy_bg;
      }
      
      
      util.downloadImagesFromUrls(imgsUrl).then(imgsUrl => { 
        console.log(imgsUrl)  
        that.goDraw(imgsUrl); 
      }).catch(err => {  
        wx.showToast({
          title: '生成失败，请稍后再试',
          icon:'none'
        })
        wx.hideLoading()
      }); 
    })
 
  }, 
  goDraw(imgsUrl){
     var that = this;
      var type_1_info = [{
          type: 'rect',
          style: {
            left: 0,
            top: 0,
            width: 560,
            height:1200,
            backgroundColor: '#ffffff'
          }
        },  {
          type: 'image',
          src:imgsUrl.cardbackground,
          style: {
            left: 0,
            top: 0,
            width: 560,
            height:450, 
          }
        },{
          type: 'image',
          src: imgsUrl.avatar,
          style: {
            left: 35,
            top:35,
            width: 128,
            height: 128, 
            borderRadius:128
          }
        }, {
          type: 'text',
          text:that.data.detail.name,
          style: {
            left:190,
            top:90, 
            fontSize: 38,
            color: '#ffffff',
            width: 560,
            fontWeight: 'bold',
            textAlign: 'left', 
          }
        }, {
          type: 'text',
          text: that.data.detail.position,
          style: {
            left: 190,
            top:140,
            fontSize:24,
            color: '#ffffff',
            width: 560,
            fontWeight: 'bold',
            textAlign: 'left',
            opacity:'.7'
          }
        }, {
          type: 'image',
          src: '/images/hb-dh.png',
          style: {
            left: '35',
            top: 200,
            width:24,
            height: 24, 
          }
        }, {
          type: 'text',
          text: that.data.detail.phone,
          style: {
            left:76,
            top:220,
            fontSize:24,
            color: '#ffffff',
            width: 560, 
            textAlign: 'left'
          }
        }, {
          type: 'image',
          src: '/images/hb-wx.png',
          style: {
            left: '35',
            top: 260,
            width:24,
            height: 24, 
          }
        }, {
          type: 'text',
          text: that.data.detail.wechat_num,
          style: {
            left: 76,
            top:280,
            fontSize:24,
            color: '#ffffff',
            width: 560, 
            textAlign: 'left'
          }
        }, {
          type: 'image',
          src: '/images/hb-yj.png',
          style: {
            left: '35',
            top: 320,
            width:24,
            height: 24, 
          }
        }, {
          type: 'text',
          text: that.data.detail.email,
          style: {
            left: 76,
            top:343,
            fontSize:24,
            color: '#ffffff',
            width: 560, 
            textAlign: 'left'
          }
        },{
          type: 'image',
          src: '/images/hb-dw.png',
          style: {
            left: '35',
            top: 380,
            width:24,
            height: 24, 
          }
        },{
          type: 'text',
          text: that.data.detail.address,
          style: {
            left: 76,
            top:403,
            fontSize:24,
            color: '#ffffff',
            width:450, 
            textAlign: 'left',
            lineHeight : 32,
            rows:2
          }
        },
        {
          type: 'text',
          text: '您好，我是'+that.data.detail.name,
          style: {
            left: 35,
            top:546,
            fontSize:34,
            color: '#000000',
            width: 560,
            fontWeight: '400',
            textAlign: 'left', 
          }
        },
        {
          type: 'text',
          text: '这是我的名片，请惠存 ~',
          style: {
            left: 35,
            top:600,
            fontSize:34,
            color: '#000000',
            width: 560,
            fontWeight: '400',
            textAlign: 'left',
            rows:2 
          }
        },
        {
          type: 'image',
          src: imgsUrl.minicode_image,
          style: {
            left: '410',
            top: 740,
            width: 120,
            height: 120,  
          }
        },{
          type: 'rect',
          style: {
            left: 35,
            top:790, 
            width:14,
            height:14,
            borderRadius:14,
            backgroundColor: '#ff7900', 
          }
        }, {
          type: 'rect',
          style: {
            left:65,
            top:790, 
            width:14,
            height:14,
            borderRadius:14,
            backgroundColor: '#ff7900', 
            opacity:'.8'
          }
        },  {
          type: 'rect',
          style: {
            left:95,
            top:790, 
            width:14,
            height:14,
            borderRadius:14,
            backgroundColor: '#ff7900', 
            opacity:'.4'
          }
        },  {
          type: 'text',
          text: '长按识别小程序码', 
          style: {
            left: 35,
            top: 850,
            fontSize: 24,
            color: '#999999',
            width: 560,  
          }
        }] 
  
      poster.draw(type_1_info, (filePath) => {
        //绘制图片路径 
        wx.hideLoading() 
        wx.showShareImageMenu({
          path: filePath,
          success(res) { 
             that.posterViewStatus = false; 
          },
          fail(res) { 
          }
       })
      }) 
  },
 
  /**
   * 生命周期函数--监听页面显示
   */
 

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline(){
    return {
      title: this.data.detail.name+'的电子名片',
      path:"/pages/card/index?card_id="+this.data.card_id+'&share=1'
    }
  },
  onShareAppMessage() { 
    return{
      title:this.data.detail.name+'的电子名片',
      path:"/pages/card/index?card_id="+this.data.card_id+'&share=1'
    }
  },
})